<?php
/**
 * controller note
 * 留言板相关功能
 */

class Controller_Note extends Controller_Base {
    
    /**
     * 留言板页
     */
    public function actionIndex() {
        
        $page = intval($this->_request->get('page', 1));
        $pageSize = intval($this->_request->get('pageSize', 10));
        $page = max(1, $page);
        $pageSize = min(100, max(1, $pageSize));
        
        try {
            $noteListInfo = Model_Note::getNoteList($page, $pageSize);
        } catch (Exception $ex) {
            $e = new Exception('获取留言板列表失败: '.$ex->getMessage(), $ex->getCode());
            V::log($e, Logger::LEVEL_DEBUG);
            return $this->_showMessage('系统繁忙，请稍后再试', self::MESSAGE_ERROR, array(array('url' => '/', 'text' => '返回首页')));
        }
        
        // 分页
        $pagination = HTML::widget('pager', array(
            'max_page' => ceil($noteListInfo['count'] / $pageSize),
            'current'  => $page,
            'template' => 'widget/pager',
        ));
        
        $tplData = array(
            'title' => 'app-demo - note',
            'count' => $noteListInfo['count'],
            'list' => $noteListInfo['list'],
            'pagination' => $pagination,
        );
        return $this->_view->renderLayout('note/index', 'layout', $tplData);
    }

    /**
     * 发布新留言
     */
    public function actionPost() {
        
        if (!$this->_request->isAjax()) {
            return $this->_response->setBody('Access Denied!');
        }
        
        $token = $this->_request->post('token');
        if (!$this->_checkCsrfToken($token)) {
            return $this->_ajaxMessage(self::CODE_PARAM_ERROR, '页面已过期，请刷新后再试');
        }
        $username = $this->_request->post('username');
        $message = $this->_request->post('message');
        
        try {
            $ret = Model_Note::postNew($username, $message);
            if (false === $ret) {
                return $this->_ajaxMessage(self::CODE_SYSTEM_ERROR, '添加留言信息失败 - 逻辑错误');
            }
            return $this->_ajaxMessage(self::CODE_SUCCESS, 'OK');
        } catch (Exception $ex) {
            $e = new Exception('添加留言信息失败: '.$ex->getMessage(), $ex->getCode());
            V::log($e, Logger::LEVEL_DEBUG);
            return $this->_ajaxMessage(self::CODE_SYSTEM_ERROR, '添加留言信息失败 - 系统错误');
        }
    }
}